import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectorRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

import { Platform, ActionSheetController, ModalController } from '@ionic/angular';

import { Camera } from '@ionic-native/camera/ngx';

import { UploadImageComponent } from '../../upload-image/upload-image.component';
import { UploadImageService } from 'src/app/shared/service/uploadImageService';
@Component({
  selector: 'app-upload-identity',
  templateUrl: './upload-identity.component.html',
  styleUrls: ['./upload-identity.component.scss'],
})
export class UploadIdentityComponent implements OnInit {
  @Input() items: any;
  @Output() updateIdentity: EventEmitter<any> = new EventEmitter();
  orgPath: any;
  isNative: boolean;
  // 上传图片
  selectImg: any;
  img: any = [];   // 图片显示
  currentItem: any = {};
  loaderToShow: any;
  imageResponse: any;
  isCompleteBatchUpload = 0;
  show = false;
  constructor(
    private modalCtrl: ModalController,
    private platform: Platform,

    private camera: Camera,
    private actionSheetCtrl: ActionSheetController,

    private sanitizer: DomSanitizer,

    private ref: ChangeDetectorRef,
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private uploadImageService: UploadImageService

  ) { }

  ngOnInit() {
    if (this.platform.is('cordova')) {
      this.isNative = true;
    } else {
      this.isNative = false;
    }
    this.items.forEach(element => {
      if (element.value.length > 0 || !element.disabled) {
        this.show = true;
      }

    });
  }

  // web 上传文件
  uploadFile(event: any, item) {
    if (item.disabled) {

      this.pageModalService.openImage_url(0, item.value);
      return;
    }

    const that = this;
    // 获得当前处理上传的对象
    this.items.forEach(element => {
      if (event.currentTarget.name === element.formKey) {
        that.currentItem = element;
      }
    });
    // this.openImageModal();
    // 2024.06.14 整合统一从uploadImageService处理
    if (event.target.files && event.target.files[0]) {
      this.selectImg = event.target.files[0];
      if (that.currentItem.valueN && that.currentItem.valueN === 'waterMark') {
        // 使用示例
        const sourceImage = URL.createObjectURL(this.selectImg); // 原始图片路径
        let watermarkImage = 'assets/fw/fengworz.png'; // 默认水印图片路径
        // 支持配置水印
        if (that.currentItem.showValue && that.currentItem.showValue.length > 0) {
          watermarkImage = that.currentItem.showValue;
        }
        this.appGlobalService.addWatermark(sourceImage, watermarkImage, (base64Image) => {
          console.log("\nbase64Image : " + base64Image);

          // 处理后的图片是base64编码的，可以直接上传
          this.uploadImageService.uploadFileForWeb(base64Image, (url) => {
            console.log('message----->' + url);
            url = url.replace('"', '').replace('"', '');
            that.currentItem.value = url;
            that.updateIdentity.emit(that.currentItem);
          });

        });

      } else {
        this.uploadImageService.uploadFileForWeb(this.selectImg, (url) => {
          console.log('message----->' + url);
          url = url.replace('"', '').replace('"', '');
          that.currentItem.value = url;
          that.updateIdentity.emit(that.currentItem);
        });

      }

    }
  }
  async openImageModal() {
    const that = this;
    const modal = await this.modalCtrl.create({
      component: UploadImageComponent,
      componentProps: {
        value: JSON.stringify(this.img),
        imgCount: 1
      }
    });
    modal.onDidDismiss().then((data) => {
      if (data.data) {
        that.img = data.data;
      }

      console.log('thatimg', that.img);
      if (that.img && that.img.length) {
        that.currentItem.value = that.img[0];
        if (that.orgPath) {
          // tslint:disable-next-line:no-string-literal
          that.currentItem["orgPath"] = that.orgPath;
        }
        that.updateIdentity.emit(that.currentItem);
      }
    });
    return await modal.present();
  }

  getBackground(image) {
    return this.sanitizer.bypassSecurityTrustStyle(`url(${image})`);
  }

  showImg(event, item) {
    if (item.disabled) {
      this.pageModalService.openImage_url(0, [item.value]);

    }
    event.stopPropagation();
    return;
  }
  // App 上传文件
  async presentAction(i, item) {
    const that = this;
    if (item.disabled) {
      this.pageModalService.openImage_url(0, [item.value]);
      return;
    }
    this.currentItem = this.items[i];
    const actionSheet = await this.actionSheetCtrl.create({
      mode: 'ios',
      cssClass: 'as_padding as_common as_border_common',
      buttons: [{
        text: '相机',
        cssClass: 'as_font_bd',
        handler: () => {
          const source = this.camera.PictureSourceType.CAMERA;
          this.uploadImageService.takePicture(source, false, (url, fileName) => {
            that.currentItem.value = url;
            if (that.orgPath) {
              // tslint:disable-next-line:no-string-literal
              that.currentItem["orgPath"] = that.orgPath;
            }
            that.updateIdentity.emit(that.currentItem);
          }, that.orgPath, item.cropperRatio, item);
        }
      }, {
        text: '从手机相册选择',
        cssClass: 'as_font_color',
        handler: () => {
          // 2024.06.14 整合统一从uploadImageService处理
          this.uploadImageService.openImgPicker((url, fileName) => {
            // 2024.06.14  回调函数中处理各自的具体业务
            const newEntry = {
              name: fileName,
              path: url
            };
            that.currentItem.value = url;
            if (that.orgPath) {
              // tslint:disable-next-line:no-string-literal
              that.currentItem["orgPath"] = that.orgPath;
            }
            that.updateIdentity.emit(that.currentItem);
            that.img.push(newEntry);
          }, 1, this.isCompleteBatchUpload, this.orgPath, item, this.ref);

        }
      },
      {
        text: '取消',
        cssClass: 'as_font_top',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();
  }

}
